package com.example.myapplication;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CurrencyApiService {
    private static final String TARGET_URL = "https://www.huilvbiao.com/bank/spdb";
    private static final ExecutorService executor = Executors.newSingleThreadExecutor();

    public interface ParserCallback {
        void onDataReady(List<Currency> currencyList);
        void onError(String message);
    }
    public static void fetchAndParseData(ParserCallback callback) {
        executor.execute(() -> {
            try {
                Document doc = Jsoup.connect(TARGET_URL)
                        .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36")
                        .timeout(15000)
                        .get();
                List<Currency> list = parseTable(doc);
                callback.onDataReady(list);
            } catch (Exception e) {
                callback.onError("数据获取失败：" + e.getMessage());
            }
        });
    }
    private static List<Currency> parseTable(Document doc) {
        List<Currency> currencyList = new ArrayList<>();
        Elements tableRows = doc.select("div.bank-table tbody tr");
        for (Element row : tableRows) {
            Elements tds = row.select("td");
            if (tds.size() < 6) continue;
            String nameCode = tds.get(0).text().trim();
            String[] parts = nameCode.split("[()]+");
            if (parts.length < 2) continue;
            String currencyName = parts[0];
            String currencyCode = parts[1];
            String sellRateStr = tds.get(4).text().trim();
            if (sellRateStr.isEmpty()) continue;
            try {
                double sellRate = Double.parseDouble(sellRateStr);
                currencyList.add(new Currency(currencyName, currencyCode, sellRate));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return currencyList;
    }
}